import Sker from '@/utils/sker'
import React, { useEffect, useMemo, useRef, useState } from 'react'
import styles from './index.module.less'
import cm from 'classnames'
import arrow from '/images/arrow.png'
import nullIcon from '/images/null-select.png'

function Select(props) {
  const { list, disabled, width = 92, placeholder = '请选择', type = 'block', currentValue, prefix = '' } = props
  const [expend, setExpend] = useState(false)
  const [selected, setSetects] = useState('')
  const contentRef = useRef(null)
  const selectEventName = useRef(Symbol('select'))

  // 动态获取当前item高度
  const height = useMemo(() => {
    if (expend) {
      return contentRef.current?.offsetHeight ?? 0
    } else {
      return 0
    }
  }, [expend])

  const titleValue = useMemo(() => {
    if (selected) {
      return list.find((item) => item.value === selected)?.label
    }
    return placeholder
  }, [selected])

  const select = (e, item) => {
    e.stopPropagation()
    setExpend(false)
    props?.onChange?.(item)
    setSetects(item.value)
  }

  // 展开收起select
  const selectClick = (ev) => {
    if (disabled) {
      return
    }
    ev.stopPropagation()
    Sker.dispatch('select', { name: selectEventName.current })
    setExpend(!expend)
  }

  // 全局click点击，Select失焦
  useEffect(() => {
    const click = () => {
      setExpend(false)
    }
    const removeListen = Sker.listen('select', (event) => {
      if (event.detail.name !== selectEventName.current) {
        setExpend(false)
      }
    })
    window.addEventListener('click', click)
    window.addEventListener('blur', click)
    return () => {
      removeListen()
      window.removeEventListener('click', click)
      window.removeEventListener('blur', click)
    }
  }, [])

  useEffect(() => {
    if (Array.isArray(currentValue)) {
      setSetects(currentValue)
    } else {
      ;(currentValue || currentValue == 0) && setSetects(currentValue)
    }
  }, [currentValue])

  return (
    <div style={{ width, display: type, ...props.style }} className={styles['select-container']}>
      <div className={cm(styles['select-title'], { [styles['disabled']]: disabled })} onClick={selectClick}>
        <div className={cm(styles['select-title-text'], 'textEllipsis')}>
          {prefix}
          {titleValue}
        </div>
        <img
          src={arrow}
          alt=""
          className={cm(styles['select-title-arrow'], expend ? styles.activeEnter : styles.activeLeave)}
        />
      </div>

      <div className={cm(styles['select-options'], !expend ? styles.unactive : styles['expend-options'])}>
        <div className={styles['select-items-box']} style={{ height: height }}>
          <div ref={contentRef} className={cm(styles['select-items'], { [styles['select-items-flex']]: !list.length })}>
            {!list.length && (
              <>
                <img src={nullIcon} alt="" />
                <div>暂无数据</div>
              </>
            )}
            {!!list.length && (
              <ul>
                {list.map((item, index) => (
                  <li
                    key={index}
                    onClick={(e) => select(e, item)}
                    className={cm(styles['select-item'], 'textEllipsis', { [styles.active]: item.value === selected })}
                  >
                    {item.label || item.value}
                  </li>
                ))}
              </ul>
            )}
          </div>
        </div>
      </div>
    </div>
  )
}

const Index = React.memo(Select)

export default Index
